package com.why.interceptors;

import cn.hutool.jwt.JWT;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.CollationKey;

/**
 * @author new wei
 * @date 2022/5/16 11:32
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (null!=cookies&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if ("LOGIN_TOKEN".equals(cookie.getName())){
                    String token = cookie.getValue();
                    // 密钥
                    byte[] key = "1234567890".getBytes();
                    JWT jwt = JWT.of(token);
                    boolean b = jwt.setKey(key).verify();
                    if (b){
                        Object uname = jwt.getPayload("uname");
                        Object uid = jwt.getPayload("uid");
                        request.setAttribute("uname",uname);
                        request.setAttribute("uid",uid);
                        return true;
                    }
                }
            }
        }
        response.sendRedirect("/user/toLogin");
        return false;
    }
}
